package echo.codec;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.util.CharsetUtil;

import java.nio.CharBuffer;
import java.util.List;
import java.util.Map;

public class ObjectDecoder extends MessageToMessageDecoder<ByteBuf> {
    private final ObjectMapper objectMapper;

    public ObjectDecoder() {
        objectMapper = new ObjectMapper();
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        if (msg instanceof Map) {
//            out.add(Unpooled);
            String s = objectMapper.writeValueAsString(msg);
            out.add(ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(s), CharsetUtil.UTF_8));
        }

    }
}
